# routers/conversation.py

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from core.database import get_db
from core.dependencies import common_dependencies
from core.schemas import ResponseModel, ConversationCreate
from core.crud import create_conversation, get_conversation, get_conversations_by_user_id

router = APIRouter(
    prefix="/conversation",
    tags=["conversation"],
    responses={404: {"description": "Not found"}},
)


@router.post("/create", response_model=ResponseModel)
async def create_conversation_endpoint(conversation: ConversationCreate, common: dict = Depends(common_dependencies)):
    db_session = create_conversation(conversation.conversation_id, common["db"], common["user_id"])
    return {"data": db_session, "code": "success", "message": "Conversation created successfully"}


@router.get("/{conversation_id}", response_model=ResponseModel)
async def get_conversation_endpoint(conversation_id: str, common: dict = Depends(common_dependencies)):
    session = get_conversation(common["db"], conversation_id=conversation_id)
    if session:
        return {"data": session, "code": "success", "message": "Conversation retrieved successfully"}
    else:
        return {"data": None, "code": "404", "message": "Conversation not found"}


@router.get("/user/{user_id}", response_model=ResponseModel)
async def get_conversations_by_user_id_endpoint(user_id: int, common: dict = Depends(common_dependencies)):
    conversations = get_conversations_by_user_id(common["db"], user_id=user_id)
    if not conversations:
        return {"data": [], "code": "success", "message": "No conversations found for this user"}
    return {"data": list(reversed(conversations)), "code": "success", "message": "Conversations retrieved successfully"}
